<template>
  <div class="custom-form">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="formData" :rules="rules" size="large" label-width="100px"
        :key="showFormKey" v-if="showForm">
        <el-col :span="7" v-show="hasFormPermission('identify_name')">
          <el-form-item :label="$t('姓名')" prop="identify_name">
            <el-input v-model="formData['identify_name']" placeholder="请输入姓名"
              :disabled="hasDisabledPermission('identify_name',false)"
              :readonly="!hasEditPermission('identify_name',true)" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
		<el-col :span="7" v-show="hasFormPermission('gender')">
			<el-form-item :label="$t('性别')" prop="gender">
				<el-select v-model="formData['gender']" placeholder="请选择性别"
					:disabled="hasDisabledPermission('gender',false)" filterable clearable
					:style="{width: '100%'}">
					<el-option v-for="(item, index) in sexOptions" :key="index" :label="item.F_ItemName"
						:value="item.F_ItemValue" :disabled="item.disabled"></el-option>
				</el-select>
			</el-form-item>
		</el-col>
		<el-col :span="7" v-show="hasFormPermission('identify_id')">
		  <el-form-item :label="$t('身份证号')" prop="identify_id">
		    <el-input v-model="formData['identify_id']" placeholder="请输入身份证号"
		      :disabled="hasDisabledPermission('identify_id',false)"
		      :readonly="!hasEditPermission('identify_id',true)" :style="{width: '100%'}"></el-input>
		  </el-form-item>
		</el-col>
		<el-col :span="7" v-show="hasFormPermission('room_number')">
		  <el-form-item :label="$t('房间号')" prop="room_number">
		    <el-input v-model="formData['room_number']" placeholder="请输入姓名"
		      :disabled="hasDisabledPermission('room_number',false)"
		      :readonly="!hasEditPermission('room_number',true)" :style="{width: '100%'}"></el-input>
		  </el-form-item>
		</el-col>
		<el-col :span="7" v-show="hasFormPermission('checkin_id')" style="display: none;">
		  <el-form-item :label="$t('checkin_id')" prop="checkin_id">
		    <el-input v-model="formData['checkin_id']" placeholder="checkin_id"
		      :disabled="hasDisabledPermission('checkin_id',true)"
		      :readonly="!hasEditPermission('checkin_id',true)" :style="{width: '100%'}"></el-input>
		  </el-form-item>
		</el-col>
        <!-- <el-col :span="7" v-show="hasFormPermission('division')">
          <el-form-item :label="$t('事业部')" prop="division">
            <el-input v-model="formData['division']" placeholder="请输入事业部"
              :disabled="hasDisabledPermission('division',false)"
              :readonly="!hasEditPermission('division',true)" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="7" v-show="hasFormPermission('department')">
          <el-form-item :label="$t('部门')" prop="department">
            <el-input v-model="formData['department']" placeholder="请输入部门"
              :disabled="hasDisabledPermission('department',false)"
              :readonly="!hasEditPermission('department',true)" :style="{width: '100%'}"></el-input>
          </el-form-item> 
        </el-col>
        
        <el-col :span="7" v-show="hasFormPermission('checkin_date')">
          <el-form-item :label="$t('入住日期')" prop="checkin_date">
            <el-date-picker :disabled="hasDisabledPermission('checkin_date',false)"
              :readonly="!hasEditPermission('checkin_date',true)" v-model="formData['checkin_date']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择入住日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('checkout_date')">
          <el-form-item :label="$t('退宿日期')" prop="checkout_date">
            <el-date-picker :disabled="hasDisabledPermission('checkout_date',false)"
              :readonly="!hasEditPermission('checkout_date',false)" v-model="formData['checkout_date']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择退宿日期" @change="changeValue($event)">
            </el-date-picker>
          </el-form-item>
        </el-col>
		<el-col :span="3" v-show="hasLookFormPermission('field177170e')">
		  <el-form-item label-width="0" prop="field177170e">
		    <el-button type="primary" @click='getField177Options()'>结算</el-button>
		  </el-form-item>
		</el-col> 
        <el-col :span="24" v-show="hasFormPermission('t_electric_checkout_settlement_details')">
          <avue-form v-loading="preloadLoading113" class=" avueFormTitleNoWrap  subTableForm "
            element-loading-text="数据预加载中..." element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.7)" :option="option113"
            v-model="t_electric_checkout_settlement_details"
            ref="avueTablet_electric_checkout_settlement_details"
            v-show="hasFormPermission('t_electric_checkout_settlement_details')" :disabled="disabled"
            v-if="reRenderSubform">
          </avue-form>
        </el-col>
		<el-col :span="24" v-show="hasFormPermission('room_tools_details')">
		  <avue-form v-loading="preloadLoading114" class=" avueFormTitleNoWrap  subTableForm "
		    element-loading-text="数据预加载中..." element-loading-spinner="el-icon-loading"
		    element-loading-background="rgba(0, 0, 0, 0.7)" :option="option114"
		    v-model="room_tools_details"
		    ref="avueTableroom_tools_details"
		    v-show="hasFormPermission('room_tools_details')" :disabled="disabled"
		    v-if="reRenderSubform">
		  </avue-form>
		</el-col>
        <el-col :span="24" >
          <el-form-item size="large" v-if="isEdit" class="form-button-center">
            <el-button type="primary" @click="submitForm" :loading="submitLoading"> 
              {{submitLoading?$t('workFlow.WFMenu.hintSubmit'):$t('submit')}}</el-button>
            <el-button @click="cancelForm">{{$t('cancelText')}}</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>

        import authorizeMixin from "@/mixins/authorize";
        import { baseUrl } from "@/config/env";
        import request from "@/router/axios";
         import {fieldsConfig,formFieldsMap,getHideComponents} from './settlementConfig'
		import { formValidateNotice } from '@/util/util';
        export default {
          mixins: [authorizeMixin],
       
  components: {},
  props: ['keyValue', 'isEdit', 'disabled','identifyName','roomNumber','Division','Department','identifyId','checkinDate','checkoutDate','checkin_id','gender'],
  data() {
    return {
      userInfo: {},
      submitLoading: false,
      showForm: true,
      showFormKey: 1,
      reRenderSubform: false,
      operationVal: 'add',
      isAdd: true,
	  jiesuan:false,
	  checkout_date:'',
      addressUrl:'settlement',
      autoCompleteConfEventData: [],
      mainTableName: 't_electric_checkout_settlement',
      formConfig: {},
      formFieldsMap: new Map(),
      hideComponentsMap: new Map(),
      needShowValueTags: ['asso-popup', 'mutiple-popup'],
	  Str:{
		  start: '',
		  end:'',
		  'roomNumber':this.roomNumber,
		  'identifyId':this.identifyId,
	  },
	  Repair:{
		  'identify_id': this.identifyId,
	  },
      formData: {
        'identify_name': this.identifyName,
		'gender':this.gender,
		'room_number':this.roomNumber,
        'division': this.Division,
        'department': this.Department,
        'identify_id': this.identifyId,
        'checkin_date': this.checkinDate,
        'checkout_date': this.checkoutDate,
		// 'field177170e': '',
		// 'issettled':1,
		'checkin_id':this.keyValue,
		// 'ispayed':"是",
      },
	  // formData2: {
	  //   'identify_name': this.identifyName,
	  // 		'gender':'',
	  // 		'room_number':this.roomNumber,
	  //   'division': this.Division,
	  //   'workshop': this.Workshop,
	  //   'identify_id': this.identifyId,
	  //   'checkin_date': this.checkinDate,
	  //   'checkout_date': this.checkoutDate,
	  // 		// 'field177170e': '',
	  // 		// 'issettled':1,
	  // 		'checkin_id':this.keyValue,
	  // 		// 'ispayed':"是",
	  // },
      rules: {
        identify_name: [],
		room_number: [],
        division: [],
        department: [],
        identify_id: [],
        checkin_date: [],
        checkout_date: [],
		gender:[],
      },
      t_electric_checkout_settlement_details: {
		  'amounts':'',
		  'iteams':'',
		  'numbers':'',
		  'prices':'',
		  'checkout_date':'',
		  'notes':'',
	  },
	  room_tools_details: {	  
	  	  'iteams':'',
	  	  'isreturn':'',
	  },
	  RepairList:{
		  'iteams':'维修赔偿',
		  'numbers':'',
		  'prices':'',
		  'amounts':'',
		  'checkout_date':'',
		  'notes':'',
	  },
	  room_toolsList: {
	  	  'iteams':'',
	  	  'isreturn':'',
	  },
	  sexOptions: [],
      preloadLoading113: false,
	  preloadLoading114:false,
    }
  },
  computed: {
    option113() {
      return {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 100,
        disabled: this.disabled,
        column: [{
          label: '费用结算',
          prop: 't_electric_checkout_settlement_details',
          type: 'dynamic',
          span: 24,
          children: {
            align: 'center',
            headerAlign: 'center',
			columnBtn:false,
			refreshBtn:false,
			addBtn:false,
			delBtn:false,
			editBtn:false,
            rowAdd: (done) => {
              // this.$message.success('新增回调');
              done({});
            },
            rowDel: (row, done) => {
              // this.reRenderSubform = false; //更新组件 index
              // setTimeout(() => {
              //   // this.$message.success('删除回调'+JSON.stringify(row));
              //   this.reRenderSubform = true;
              // }, 0);
              done();
            },
            column: this.getAuthorityTableChildrenList('t_electric_checkout_settlement_details', [{
              label: this.$t('费用项目'),
              prop: 'iteams',
              value: '',
              type: 'input-tip',
              width: null,
              placeholder: '请输入费用项目',
              required: true,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [{
                required: true,
                message: '费用项目不能为空'
              }, ],
              ruleList: [{
                required: true,
                message: '费用项目不能为空'
              }, ],
            }, {
              label: this.$t('数量'),
              prop: 'numbers',
              value: '',
              type: 'input',
              width: null,
              placeholder: '请输入数量',
              required: true,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [{
                required: true,
                message: '数量不能为空'
              }, ],
              ruleList: [{
                required: true,
                message: '数量不能为空'
              }, ],
            }, {
              label: this.$t('单价'),
              prop: 'prices',
              value: '',
              type: 'input',
              width: null,
              placeholder: '请输入单价',
              required: false,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [],
              ruleList: [{
                required: true,
                message: '单价不能为空'
              }, ],
            }, {
              label: this.$t('金额'),
              prop: 'amounts',
              value: '',
              type: 'input',
              width: null,
              placeholder: '请输入金额',
              required: false,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [
	        {
	          pattern: /^(\+)?\d+(\.\d+)?$/,
	          message: '格式错误',
	          trigger: 'blur'
	        }			  
			  ],
              ruleList: [{
                required: true,
                message: '金额不能为空'
              }, ],
            }, {
              label: this.$t('结算日期'),
              prop: 'checkout_date',
              value: '',
              type: 'date',
              width: null,
              placeholder: '请选择结算日期',
              // 'value-format': 'yyyy-MM-dd',
              // format: 'yyyy-MM-dd',
              required: true,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [],
              ruleList: [{
                required: true,
                message: '结算日期不能为空'
              }, ],
            }, {
              label: this.$t('备注'),
              prop: 'notes',
              value: '',
              type: 'input-tip',
              width: null,
              placeholder: '请输入备注',
              required: false,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [{
                required: true,
                message: '备注不能为空'
              }, ],
              ruleList: [{
                required: true,
                message: '备注不能为空'
              }, ],
            }, ])
          }
        }, ],
      }
    },
	option114() {
	  return {
	    submitBtn: false,
	    emptyBtn: false,
	    labelWidth: 100,
	    disabled: this.disabled,
	    column: [{
		  cascader:['point'],
	      label: '房间物品',
	      prop: 'room_tools_details',
	      type: 'dynamic',
	      span: 24,
	      children: {
	        align: 'center',
	        headerAlign: 'center',
			columnBtn:false,
			refreshBtn:false,
			addBtn:false,
			delBtn:false,
			editBtn:false,
	        rowAdd: (done) => {
	          // this.$message.success('新增回调');
	          done({});
	        },
	        rowDel: (row, done) => {
	          // this.reRenderSubform = false; //更新组件 index
	          // setTimeout(() => {
	          //   // this.$message.success('删除回调'+JSON.stringify(row));
	          //   this.reRenderSubform = true;
	          // }, 0);
	          done();
	        },
	        column: this.getAuthorityTableChildrenList('room_tools_details', [{
			 
	          label: this.$t('物品名称'),
	          prop: 'iteams',
	          value: '',
	          type: 'input-tip',
	          width: null,
	          placeholder: '请输入物品名称',
	          required: true,
	          formslot: false,
	          disabled: true,
	          rules: [{
	            required: true,
	            message: '物品名称不能为空'
	          }, ],
	          ruleList: [{
	            required: true,
	            message: '物品名称不能为空'
	          }, ],
	        },
			{
	          label: this.$t('是否归还'),
	          prop: 'isreturn',
	          value: '',
	          type: 'select',
	          width: null,
			  props:{
			  	label:'F_ItemName',
			  	 value:'F_ItemValue'
			  },
			  dicUrl:baseUrl + '/data-items/isreturn/detail',
	          placeholder: '请选择是否归还',
	          required: true,
	          formslot: false,
	          disabled: this.disabled ? this.disabled : false,
	          rules: [{
	            required: true,
	            message: '请选择是否归还',
				trigger:'blur'
	          }, ],
	          ruleList: [{
	            required: true,
	            message: '请选择是否归还'
	          }, ],
	        }, ])
	      }
	    }, ],
	  }
	},
  },
  watch: {},
  async created() {
    this.formConfig = this.getFormConfig();
    this.formFieldsMap = this.getFormFieldsMap();
    this.userInfo = localStorage.getItem("avue-userInfo") ? JSON.parse(localStorage.getItem(
      "avue-userInfo")).content : {};
	  // if(this.formData.gender=="男"){
		 //  this.formData2.gender = 1
	  // }
	  // else{
		 //  this.formData2.gender = 0
	  // }
	  // console.log(this.formData2.gender)
  },
  async mounted() {
    this.hideComponentsMap = await this.getHideComponentsMap();
    this.showForm = false;
    await this.insertCreatedEvent();
	if (typeof this.getField103Options == "function") {
		await this.getField103Options();
	}
    //TODO   再这里做数据回填 请求表单数据
   
      //      if(this.keyValue){
      //         this.isAdd = false;
      //     }
      //      if(!this.isAdd&&this.keyValue){
      //         this.operationVal = 'edit';
      //         try {
      //           let res = await request({
      //             url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
      //             method: "get",
      //           });
                  
      //       this.formData = res.data.data.t_electric_checkout_settlement
            
      //     this.t_electric_checkout_settlement_details.t_electric_checkout_settlement_details = res.data.data.t_electric_checkout_settlement_details
          
      //   this.t_electric_checkout_settlement_details.t_electric_checkout_settlement_details.forEach(element => {
      // });
      
      //             await this.handleEdit();
      //            this.showFormKey++;
      //         } catch (error) {
      //         }
      //     }

       // if(this.keyValue){
       //     this.isAdd = false;
       // }
       //  if(!this.isAdd&&this.keyValue){
       //     this.operationVal = 'edit';
       //     try {
       //       let res = await request({
       //         url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
       //         method: "get",
       //       });
               
       //   this.formData = res.data.data
         
       //         await this.handleEdit();
       //        this.showFormKey++;
       //     } catch (error) {
       //     }
       // }
       
             
    await this.insertMountedEvent();
    this.reRenderSubform = true; //子表单显示
    this.showFormKey++;
    this.processParameterAssignment();
    this.showForm = true;
  },
  methods: {
    getFormData() {
      let key = this.mainTableName + 'Entity';
      let returnParams = {};
      returnParams[key] = this.formData;
      return {
        ...returnParams,
        t_electric_checkout_settlement_detailsEntityList: this.t_electric_checkout_settlement_details.t_electric_checkout_settlement_details,
		t_electric_checkout_settlement_toolsEntityList:this.room_tools_details.room_tools_details,
      };
    },
    validateForm() {
      this.$refs['elForm'].validate(valid => {});
    },
	changeValue(e) {
		this.checkout_date = e;
		let end = e;
		console.log(e)
		var year = end.substr(0,4);
		var month = end.substr(5,2);
		this.Str.start = year + '-' + month + '-01';
		this.Str.end = e;
		// console.log(this.Str.end)
		localStorage.setItem("checkout_date1",e);
		
		// this.electricCost.checkout_date = e;
		
		// localStorage.setItem("end",end1);
		// localStorage.setItem("start",start1);
		// console.log(this.Str)
		
		// let start 
	},
    async aysncValidateForm() {
      let validataArry = []
      let formValidateNotice = function formValidateNotice(obj, that, formAuth) {
        for (var o in obj) {
          if (!formAuth[o] && obj[o][0]) {
            that.$message({
              message: obj[o][0].message + ',' + that.$t('noFormAuth'),
              type: 'warning'
            });
            return;
          }
        }
      }
      if (this.t_electric_checkout_settlement_details.t_electric_checkout_settlement_details && this
        .t_electric_checkout_settlement_details.t_electric_checkout_settlement_details.length > 0) {
        validataArry.push(new Promise((resolve, reject) => {
          this.$refs['avueTablet_electric_checkout_settlement_details'].validate(valid => {
            resolve(valid)
          });
        }));
      }
	  if (this.room_tools_details.room_tools_details && this
	    .room_tools_details.room_tools_details.length > 0) {
	    validataArry.push(new Promise((resolve, reject) => {
	      this.$refs['avueTableroom_tools_details'].validate(valid => {
	        resolve(valid)
	      });
	    }));
	  }
      validataArry.push(new Promise((resolve, reject) => {
        this.$refs['elForm'].validate((valid, object) => {
          if (!this.isWorkflowForm) formValidateNotice(object, this, this.formEnCodeList)
          resolve(valid)
        })
      }))
      let res = await Promise.all(validataArry)
      if (res.includes(false)) {
        return false
      }
      else {
        return true;
      }
    },
    changeTableData() {
      if (this.t_electric_checkout_settlement_details.t_electric_checkout_settlement_details && this
        .t_electric_checkout_settlement_details.t_electric_checkout_settlement_details.length > 0) {
        this.t_electric_checkout_settlement_details.t_electric_checkout_settlement_details.forEach((element,
          index) => {
          let itemChild = {
            ...element
          }
          for (let [key, value] of Object.entries(itemChild)) {
            if (Array.isArray(value)) {
              itemChild[key] = value.join(',')
            }
          }
          this.t_electric_checkout_settlement_details.t_electric_checkout_settlement_details[index] =
            itemChild;
        });
      }
      else {
        this.t_electric_checkout_settlement_details.t_electric_checkout_settlement_details = [];
      }
    },
	changeTableData2() {
	  if (this.room_tools_details.room_tools_details && this
	    .room_tools_details.room_tools_details.length > 0) {
	    this.room_tools_details.room_tools_details.forEach((element,
	      index) => {
	      let itemChild = {
	        ...element
	      }
	      for (let [key, value] of Object.entries(itemChild)) {
	        if (Array.isArray(value)) {
	          itemChild[key] = value.join(',')
	        }
	      }
	      this.room_tools_details.room_tools_details[index] =
	        itemChild;
	    });
	  }
	  else {
	    this.room_tools_details.room_tools_details = [];
	  }
	},
	async getField177Options() { 
	 
	  // localStorage.setItem("jiesuan",true);
	  let newObj = this.Str;
	  let newObj2 = this.Repair;
	  let arr = [];
	  // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
	  try {
	    let res = await this.$axios({
	      method: 'get',
	      url:  baseUrl + '/electricmeter/settlement',
		  params: newObj
	    });
		let res2 =  await this.$axios({
	      method: 'get',
	      url:  baseUrl + '/repair',
		  params: newObj2
	    });
		let res3 =  await this.$axios({
		  method: 'get',
		  url:  baseUrl + '/room_tools',
		  
		});
		this.RepairList = res2.data.data.Rows;
		this.room_toolsList = res3.data.data.Rows;
		// this.RepairList.notes=res2.data.data.Rows[0].items;
		for(let i = 0;i<res2.data.data.Total;i++)
		if(res2.data.data.Rows[i].ispayed==0){
			this.RepairList[i].notes=res2.data.data.Rows[i].items;
			this.RepairList[i].prices=res2.data.data.Rows[i].amounts;
			this.RepairList[i].numbers=1;
			this.RepairList[i].iteams = '维修赔偿';
			this.RepairList[i].checkout_date=this.Str.end;
			this.RepairList=this.RepairList[i];
			
		}
		for(let a = 0;a<res3.data.data.Total;a++){
			this.room_toolsList[a].iteams = res3.data.data.Rows[a].tool_name;;
		}
		// console.log(this.RepairList2)
		console.log(this.room_toolsList)
		console.log(this.RepairList)
		this.jiesuan = true;
		console.log(this.jiesuan)
		this.t_electric_checkout_settlement_details.t_electric_checkout_settlement_details=res.data.data.concat(this.RepairList);
		this.room_tools_details.room_tools_details=this.room_toolsList;
	  }
	  catch (error) {
		 console.log(123)
	  }
	},
	async getField103Options() {
		// 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
		try {
			let resp = await this.$axios({
				method: 'get',
				url: baseUrl + '/data-items/sex/detail',
			});
			if (resp.data.data) {
				this.sexOptions = resp.data.data;
	
			}
		} catch (error) {}
	},
    async submitForm() {
		// console.log(localStorage.getItem("jiesuan"))
		// if(this.jiesuan==false){
		// 	this.submitLoading = false;
		// 	this.$notify({
		// 	  title: "失败", 
		// 	  message: "请选择退宿日期并结算",
		// 	  type: "warning",
		// 	});
		// }
		 //    let jiesuan = localStorage.getItem("jiesuan");
			// console.log(jiesuan)
			this.submitLoading = true;
			  let valid = await this.aysncValidateForm();
			  if (valid == false) {
			    this.submitLoading = false;
			    return false;
			  }
			  this.changeTableData();
			  this.changeTableData2();
			  //格式化数据
			  let newObj = this.getFormData();
			  if(newObj.t_electric_checkout_settlementEntity.gender == "男"){
			  				  newObj.t_electric_checkout_settlementEntity.gender = 0
			  }
			  else{
			  				  newObj.t_electric_checkout_settlementEntity.gender = 1
			  }
			    //如果没有传入参数就是新增
			    if (!this.keyValue) {
					if(this.jiesuan==false){
						this.submitLoading = false;
						this.$notify({
						  title: "失败", 
						  message: "请选择退宿日期并结算",
						  type: "warning",
						});
					}
			else{
			      request({
			        url: baseUrl + "/"+this.addressUrl,
			        method: "post",
			        data : newObj 
			      }).then((res) => {
			        this.submitLoading = false;
			        this.$notify({
			          title: "成功",
			          message: "退宿成功",
			          type: "success",
			        });
			         this.$emit("onChange",true)
			      });
			
			    }}
			    else{
			if(this.jiesuan==false||this.checkout_date == ''){
				this.submitLoading = false;
				this.$notify({
				  title: "失败", 
				  message: "请选择退宿日期并结算",
				  type: "warning",
				});
			}
			else{
				request({
			        url: baseUrl + "/"+this.addressUrl,
			        method: "post",
			        data : newObj
			      }).then((res) => {
			        this.submitLoading = false;
			        this.$notify({
			          title: "成功",
			          message: "退宿成功",
			          type: "success",
			        });
			         this.$emit("onChange",true)
			      });
			
			    }
			     }
			  await this.handleSubmit();		
		
      },
    cancelForm() {
      this.$emit("onChange", true)
    },
    formatTree(data, valueField, lableField, childField, type) {
      let tree = [];
      data.forEach((node, index) => {
        let newNode = {
          value: node[valueField],
          label: node[lableField],
        };
        if (type) {
          newNode.disabled = node[valueField] == undefined ? true : false
        }
        tree.push(newNode);
        if (node[childField] != null && node[childField].length > 0) {
          newNode.children = (this.formatTree(node[childField], valueField, lableField, childField,
          type));
        }
      }, this);
      return tree;
    },
    
          //辅助编辑 预留方法
          async handleEdit() {
            await this.insertEditEvent();
          },
          
    //FORM_EVENT_EDIT
    
        //辅助提交 预留方法
        async handleSubmit() {
          await this.insertSubmitEvent();
        },
        //辅助工作流提交 预留方法
        getHandleSubmitFormEvent() {
            
        },
        //辅助工作流表单事件 判断 表单事件是否已经执行过
        getisExecutedFormEvent() {
            let key = 'index'+this.$store.state.formParser.workflowFormTabIndexKey;
            return this.$store.state.formParser.isExecutedFormEvent[key]?this.$store.state.formParser.isExecutedFormEvent[key]:false;
            
        },
      
    async triggerEventHandler(eventData) {
      if (eventData.length > 0) {
        eventData.forEach(ele => {
          let functionName = 'getField' + ele.componentFormId + 'Options';
          if (typeof this[functionName] == "function") {
            this[functionName]();
          }
        })
      }
    },
    triggerEventFormIdHandler(formId) {
      if (this.formFieldsMap.get(formId).__config__.triggerEvents && this.formFieldsMap.get(formId).__config__
        .triggerEvents.length > 0) {
        this.formFieldsMap.get(formId).__config__.triggerEvents.forEach(triggerEventItem => {
          if (this.formFieldsMap.get(formId).__config__.triggerEventData && this.formFieldsMap.get(formId)
            .__config__.triggerEventData[triggerEventItem] && this.formFieldsMap.get(formId).__config__
            .triggerEventData[triggerEventItem].length > 0) {
            this.triggerEventHandler(this.formFieldsMap.get(formId).__config__.triggerEventData[
              triggerEventItem]);
          }
        });
      }
      return true;
    },
    //清空联想弹层、多选弹层的值
    clearBombLayerFormData(filed) {
      this.formData[filed] = '';
      this.formData[filed + '_showValue'] = '';
    },
    // 流程参数赋值
    processParameterAssignment() {
      // 流程中的流程参数赋值 优先级最高，最后赋值
      setTimeout(() => {
        if (this.isEdit != 2 && this.parameter && this.parameter[this.mainTableName]) {
          this.showForm = false;
          for (let [key, value] of Object.entries(this.parameter[this.mainTableName])) {
            this.setFormDataValue(key, value);
          }
          this.showForm = true;
        }
      }, 0);
    },
    setFormDataValue(field, val) {
      if (Array.isArray(this.formData[field])) {
        if (val.includes(',')) {
          this.formData[field] = val.split(',');
        }
        else {
          this.formData[field] = [val];
        }
      }
      else {
        this.formData[field] = val;
      }
      //处理联想弹层，多选弹层
      if (this.formData[field + '_showValue'] != undefined) {
        this.formData[field + '_showValue'] = val;
      }
    },
    setOutputsValue(nodeType, formId, res, outputKey) {
      let nodeTypeChecked = false;
      if (nodeType == 'created') {
        nodeTypeChecked = this.operationVal == 'add';
      }
      else if (nodeType == 'edit') {
        nodeTypeChecked = this.operationVal == 'edit';
      }
      else if (nodeType == 'mounted') {
        nodeTypeChecked = this.operationVal == 'add' || this.operationVal == 'edit';
      }
      if (nodeTypeChecked && this.disabled != true && res && res.data && res.data.data && this.formFieldsMap
        .has(formId) && this.formFieldsMap.get(formId).__vModel__ && this.formData.hasOwnProperty(this
          .formFieldsMap.get(formId).__vModel__)) {
        this.setFormDataValue(this.formFieldsMap.get(formId).__vModel__, res.data.data[outputKey]);
        // 联想弹层 多选弹层 特殊处理
        if (this.formFieldsMap.get(formId).__config__ && this.formFieldsMap.get(formId).__config__.avueType &&
          this.needShowValueTags.includes(this.formFieldsMap.get(formId).__config__.avueType)) {
          this.formData[this.formFieldsMap.get(formId).__vModel__ + '_showValue'] = res.data.data[outputKey];
        }
        this.triggerEventFormIdHandler(formId);
      }
    },
    //子表单权限
    getAuthorityTableChildrenList(bindTable, children) {
      let column = [];
      if (bindTable && this.formEnCodeList && this.formEnCodeList[bindTable]) {
        let formSubEnCodeList = this.formEnCodeList[bindTable];
        if (children && children.length > 0) {
          column = children.map(ele2 => {
            if (formSubEnCodeList.includes(ele2.prop)) {
              ele2.hide = false;
            }
            else {
              ele2.hide = true;
            }
            if (ele2.hide == false) {
              //工作流中系统表单必填权限
              if (this.formSubTableNotRequiredList && this.formSubTableNotRequiredList[bindTable] !=
                undefined) {
                if (this.formSubTableNotRequiredList[bindTable].includes(ele2.prop)) {
                  ele2.required = false;
                }
                else {
                  ele2.required = true;
                }
              }
              ele2.rules = [];
              if (ele2.required) {
                ele2.rules = ele2.ruleList;
              }
              // disabled 属性
              if (this.formSubTableDisabledList && this.formSubTableDisabledList[bindTable] !=
                undefined) {
                if (this.formSubTableDisabledList[bindTable].includes(ele2.prop)) {
                  ele2.disabled = true;
                }
                else {
                  ele2.disabled = false;
                }
              }
              if (this.disabled) { //查看
                ele2.disabled = true;
              }
            }
            else {
              ele2.rules = []
              if (ele2.required) {
                ele2.ruleList.forEach(el => {
                  el.message += ',' + this.$t('noFormAuth')
                })
                ele2.rules = ele2.ruleList;
              }
            }
            return ele2;
          });
        }
        return column;
      }
      else {
        return children;
      }
    },
    async insertCreatedEvent() {
      
    },
    async insertMountedEvent() {
      
    },
    async insertEditEvent() {
      
    },
    async insertSubmitEvent() {
      
    },
    getFormConfig() {
       return fieldsConfig();
    },
    getFormFieldsMap() {
       return formFieldsMap();
    },
    async getHideComponentsMap() {
      let mapList = new Map();
      let hideComponentList = this.getHideComponents();
      if (typeof this.initHideComponentList == 'function') {
        mapList = await this.initHideComponentList(hideComponentList);
        this.$store.commit("SET_HIDE_COMPONENT_LIST", mapList);
      }
      return mapList;
    },
    getHideComponentsMapItem(key) {
      if (this.hideComponentsMap.size > 0) {
        return this.hideComponentsMap.has(key) ? this.hideComponentsMap.get(key) : "";
      }
      else {
        return ""
      }
    },
    getHideComponents() {
       return getHideComponents();
    },
  }
}

</script>
<style>
.el-table__empty-block {
  width: 100% !important;
}

.avue-form__row {
  padding: 0 !important;
}

#editorphone {
  width: 375px;
  margin: 0 auto;
  border: 1px solid #E4E7ED;
  padding: 0 7.5px;
  background: #f5f6fa;
  height: 700px;
  overflow-y: auto;
  overflow-x: hidden;
  border-radius: 5px;
}

#editorphone .el-col {
  border-bottom: 1px solid #F2F2F2;
  background: #fff;
  margin-bottom: 0;
  padding: 0 15px 6px !important;
  width: 100%;
}

#editorphone .el-form-item__label {
  line-height: 20px
}

#editorphone .el-input-group .el-input__inner {
  background: #f5f6fa
}

#editorphone .el-input__inner {
  border: 0
}

#editorphone .el-input-group__append,
#editorphone .el-input-group__prepend {
  border: 0;
  background: #edeef2;
  color: #666;
}

#editorphone .el-input-group .el-input__prefix {
  left: 44px
}

#editorphone .el-input-group .el-input__suffix {
  right: 44px
}

#editorphone .el-form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-flow: wrap;
}

#editorphone .el-form-item__label {
  float: none;
  min-width: 85px;
  width: auto !important;
  text-align: left;
  flex: auto;
}

#editorphone .tinymce .el-form-item__label {
  min-width: 100%;
}

#editorphone .el-form-item__content {
  margin-left: 0px !important;
  flex: auto;
  width: calc(100% - 95px);
}

#editorphone .avueFormNoLable .el-form-item__label,
#editorphone .avueFormNoLable .avue-crud__pagination {
  display: none;
}

#editorphone .avueFormNoLable .el-collapse-item__wrap,
#editorphone .avueFormNoLable .el-collapse {
  border-bottom: 0
}

#editorphone .avueFormNoLable .el-col {
  border-bottom: 0;
  padding-bottom: 0
}

#editorphone .el-form-item__content .el-button:first-child {
  margin-left: 90px;
}

</style>
